package com.ydzt.fanka.server.persistence;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.log4j.Logger;

import com.ydzt.fanka.server.domain.BufferRecord;
import com.ydzt.fanka.server.init.InitData;
import com.ydzt.fanka.server.utils.ByteConvert;

public class BufferStore {
	static Logger logger = Logger.getLogger(BufferStore.class.getName());
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	public synchronized static int writePackageIntoOnlyRead(BufferRecord record){
		int flag = -1;
		String filename = record.getBufferId();
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.onlyReadPath);
		strBuilder.append("/");
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		
		try {
			outSTr = new FileOutputStream(new File(strBuilder.toString()));
			buff = new BufferedOutputStream(outSTr);
			buff.write(record.getBufferContent());
			flag = 0;
			buff.flush();
			outSTr.flush();
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage());
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		finally{
			try{
				buff.close();
				outSTr.close();
				strBuilder.delete(0, strBuilder.length());
			}
			catch(IOException iex){
				logger.error(iex.getMessage(), iex);
			}
		}
		return flag;
	}
	
	
	public synchronized static int writePackageIntoOnlyRead(BufferRecord record,String node){
		int flag = -1;
		String filename = record.getBufferId();
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.onlyReadPath);
		strBuilder.append("/");
		strBuilder.append(node);
		strBuilder.append("/");
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		
		try {
			outSTr = new FileOutputStream(new File(strBuilder.toString()));
			buff = new BufferedOutputStream(outSTr);
			buff.write(record.getBufferContent());
			flag = 0;
			buff.flush();
			outSTr.flush();
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage());
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
		finally{
			try{
				
				buff.close();
				
				outSTr.close();
				strBuilder.delete(0, strBuilder.length());
			}
			catch(IOException iex){
				logger.error(iex.getMessage(), iex);
			}
		}
		return flag;
	}
	
	public synchronized static boolean writePackageIntoBackupTransmit(byte[] pkg){
		boolean flag = false;
		//int n = count ++;
		String filename = UUID.randomUUID().toString();
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.backup_transmitPath);
		strBuilder.append("/");
		Date today = new Date();
		String todayFile = sdf.format(today);
		strBuilder.append(todayFile);
		File backupFile = new File(strBuilder.toString());
		if(!backupFile.isDirectory()){
			backupFile.mkdir();
		}
		strBuilder.append("/");
		byte[] msgTypeByte = new byte[2];
		System.arraycopy(pkg, 0, msgTypeByte, 0, 2);
		String msgType = ByteConvert.bcd2Str(msgTypeByte);
		strBuilder.append(msgType);
		File msgTypeFile = new File(strBuilder.toString());
		if(!msgTypeFile.isDirectory()){
			msgTypeFile.mkdir();
		}
		File todayBackupFile = new File(strBuilder.toString());
		if(!todayBackupFile.isDirectory()){
			todayBackupFile.mkdir();
		}
		strBuilder.append("/");
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		
		//System.out.println(n);
		
		try {
			outSTr = new FileOutputStream(new File(strBuilder.toString()));
			buff = new BufferedOutputStream(outSTr);
			buff.write(pkg);
			flag = true;
			//System.out.println(n);
		} catch (FileNotFoundException e) {
			flag = false;
			logger.error("��Ϊbackup_transmitʧ��!");
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			flag = false;
			logger.error("��Ϊbackup_transmitʧ��!");
			logger.error(e.getMessage(), e);
		}
		finally{
			try{
				pkg = null;
				buff.flush();
				outSTr.flush();
				buff.close();
				outSTr.close();
				strBuilder.delete(0, strBuilder.length());
			}
			catch(IOException iex){
				
			}
		}
		return flag;
	}
	
	public synchronized static boolean writePackageIntoBackup(BufferRecord bufferRecord){
		boolean flag = false;
		byte[] pkg = bufferRecord.getBufferContent();
		//int n = count ++;
		String filename = bufferRecord.getBufferId();
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.backupPath);
		Date today = new Date();
		String todayFile = sdf.format(today);
		strBuilder.append(todayFile);
		File backupFile = new File(strBuilder.toString());
		if(!backupFile.isDirectory()){
			backupFile.mkdir();
		}
		strBuilder.append("/");
		byte[] msgTypeByte = new byte[2];
		System.arraycopy(pkg, 0, msgTypeByte, 0, 2);
		String msgType = ByteConvert.bcd2Str(msgTypeByte);
		strBuilder.append(msgType);
		File msgTypeFile = new File(strBuilder.toString());
		if(!msgTypeFile.isDirectory()){
			msgTypeFile.mkdir();
		}
		/*
		File todayBackupFile = new File(strBuilder.toString());
		if(!todayBackupFile.isDirectory()){
			todayBackupFile.mkdir();
		}
		*/
		strBuilder.append("/");
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		try {
			outSTr = new FileOutputStream(new File(strBuilder.toString()));
			buff = new BufferedOutputStream(outSTr);
			buff.write(pkg);
			flag = true;
			
		} catch (FileNotFoundException e) {
			flag = false;
			//e.printStackTrace();
			logger.info("д�ļ�" + strBuilder.toString() + "ʧ��");
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			flag = false;
			logger.info("д�ļ�" + strBuilder.toString() + "ʧ��");
			logger.error(e.getMessage(), e);
		}
		finally{
			try{
				pkg = null;
				buff.flush();
				outSTr.flush();
				buff.close();
				outSTr.close();
				strBuilder.delete(0, strBuilder.length());
			}
			catch(IOException iex){
				logger.error(iex.getMessage(), iex);
			}
		}
		return flag;
	}
	
	
	public synchronized static boolean writePackageIntoTransmit(BufferRecord bufferRecord){
		boolean flag = false;
		StringBuilder strBuilder = new StringBuilder();
		byte[] msgTypeByte = new byte[2];
		System.arraycopy(bufferRecord.getBufferContent(), 0, msgTypeByte, 0, 2);
		String msgType = ByteConvert.bcd2Str(msgTypeByte);
		strBuilder.append(InitData.transmitPath);
		strBuilder.append("/");
		strBuilder.append(msgType);
		File msgTypeFile = new File(strBuilder.toString());
		if(!msgTypeFile.isDirectory()){
			msgTypeFile.mkdir();
		}
		strBuilder.append("/");
		String filename = bufferRecord.getBufferId();
		String filenameSuffix = ".hex";
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		try {
			File f = new File(strBuilder.toString());
			f.setWritable(true, false);
			outSTr = new FileOutputStream(f);
			buff = new BufferedOutputStream(outSTr);
			buff.write(bufferRecord.getBufferContent());
			flag = true;
		} catch (FileNotFoundException e) {
			logger.info(strBuilder.toString() + "存入transmit失败");
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.info(strBuilder.toString() + "存入transmit失败");
			logger.error(e.getMessage(), e);
		}
		finally{
			strBuilder.delete(0, strBuilder.length());
			try {
				buff.close();
				outSTr.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return flag;
	}
	
	public synchronized static boolean writePackageIntoErrorFile(BufferRecord record,String errorType){
		boolean flag = false;
		Date today = new Date();
		String filename = record.getBufferId();
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.errorPath);
		strBuilder.append("/");
		String todayFile = sdf.format(today);
		strBuilder.append(todayFile);
		File backupFileDate = new File(strBuilder.toString());
		if(!backupFileDate.isDirectory()){
			backupFileDate.mkdir();
		}
		strBuilder.append("/");
		strBuilder.append(errorType);
		File backupFile = new File(strBuilder.toString());
		if(!backupFile.isDirectory()){
			backupFile.mkdir();
		}
		strBuilder.append("/");
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		
		try {
			outSTr = new FileOutputStream(new File(strBuilder.toString()));
			buff = new BufferedOutputStream(outSTr);
			buff.write(record.getBufferContent());
			flag = true;
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		finally{
			try{
				buff.close();
				outSTr.close();
				strBuilder.delete(0, strBuilder.length());
			}
			catch(IOException iex){
				logger.error(iex.getMessage(), iex);
			}
		}
		return flag;
	}
	
	public synchronized static int writePackageIntoBroadcastBackup(byte[] pkg){
		int n = -1;
		String filename = UUID.randomUUID().toString();
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.backup_broadcast);
		strBuilder.append("/");
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		
		try {
			File f = new File(strBuilder.toString());
			f.setWritable(true, false);
			outSTr = new FileOutputStream(f);
			buff = new BufferedOutputStream(outSTr);
			buff.write(pkg);
			n = 0;
			//System.out.println("д��" + n + "����");
		} catch (FileNotFoundException e) {
			logger.info("备份" + strBuilder.toString() + "失败");
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.info("备份" + strBuilder.toString() + "失败");
			logger.error(e.getMessage(), e);
		}
		finally{
			strBuilder.delete(0, strBuilder.length());
			try {
				buff.close();
				outSTr.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return n;
	}
	
	public synchronized static int writePackageIntoTransmitBackup(byte[] pkg){
		int n = -1;
		String filename = UUID.randomUUID().toString();
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.backup_transmitPath);
		strBuilder.append("/");
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		
		try {
			File f = new File(strBuilder.toString());
			f.setWritable(true, false);
			outSTr = new FileOutputStream(f);
			buff = new BufferedOutputStream(outSTr);
			buff.write(pkg);
			n = 0;
			//System.out.println("д��" + n + "����");
		} catch (FileNotFoundException e) {
			logger.info("备份" + strBuilder.toString() + "失败");
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.info("备份" + strBuilder.toString() + "失败");
			logger.error(e.getMessage(), e);
		}
		finally{
			strBuilder.delete(0, strBuilder.length());
			try {
				buff.close();
				outSTr.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return n;
	}
	
	
	public synchronized static int writePackageIntoWaitTransmit(BufferRecord bufferRecord){
		int n = -1;
		String filename = UUID.randomUUID().toString();
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.wait_transmitPath);
		strBuilder.append("/");
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		
		try {
			File f = new File(strBuilder.toString());
			f.setWritable(true, false);
			outSTr = new FileOutputStream(f);
			buff = new BufferedOutputStream(outSTr);
			buff.write(bufferRecord.getBufferContent());
			n = 0;
			//System.out.println("д��" + n + "����");
		} catch (FileNotFoundException e) {
			logger.info("д�ļ�" + strBuilder.toString() + "ʧ��");
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.info("д�ļ�" + strBuilder.toString() + "ʧ��");
			logger.error(e.getMessage(), e);
		}
		finally{
			strBuilder.delete(0, strBuilder.length());
			try {
				buff.close();
				outSTr.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return n;
	}
	
	
	public synchronized static int writePackageIntoBroadcast(BufferRecord bufferRecord){
		String filename = bufferRecord.getBufferId();
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.broadcastdir);
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		
		try {
			File f = new File(strBuilder.toString());
			f.setWritable(true, false);
			outSTr = new FileOutputStream(f);
			buff = new BufferedOutputStream(outSTr);
			buff.write(bufferRecord.getBufferContent());
		} catch (FileNotFoundException e) {
			logger.error("保存文件" + strBuilder.toString() + "进broadcast文件夹失败");
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error("保存文件" + strBuilder.toString() + "进broadcast文件夹失败");
			logger.error(e.getMessage(), e);
		}
		finally{
			strBuilder.delete(0, strBuilder.length());
			try {
				buff.close();
				outSTr.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return 0;
	}
	
	public synchronized static int writePackageIntoEndFlag(byte[] pkg){
		String filename = "endday";
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.endflag);
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		try {
			File f = new File(strBuilder.toString());
			f.setWritable(true, false);
			outSTr = new FileOutputStream(f,false);//如果文件存在则覆盖
			buff = new BufferedOutputStream(outSTr);
			buff.write(pkg);
			
		} catch (FileNotFoundException e) {
			logger.error("保存文件" + strBuilder.toString() + "进ENDFLAG文件夹失败");
			logger.error(e.getMessage(), e);
			return -1;
		} catch (IOException e) {
			logger.error("保存文件" + strBuilder.toString() + "进ENDFLAG文件夹失败");
			logger.error(e.getMessage(), e);
			return -1;
		}
		finally{
			strBuilder.delete(0, strBuilder.length());
			try {
				buff.close();
				outSTr.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
		}
		return 0;
	}
	
	public synchronized static int writePackageIntoFile(BufferRecord record){
		String filename = record.getBufferId();
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.bufferPath);
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		
		try {
			File f = new File(strBuilder.toString());
			f.setWritable(true, false);
			outSTr = new FileOutputStream(f);
			buff = new BufferedOutputStream(outSTr);
			buff.write(record.getBufferContent());
			logger.error("保存文件" + strBuilder.toString() + "进buffer文件夹成功");
		} catch (FileNotFoundException e) {
			logger.error("保存文件" + strBuilder.toString() + "进buffer文件夹失败");
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error("保存文件" + strBuilder.toString() + "进buffer文件夹失败");
			logger.error(e.getMessage(), e);
		}
		finally{
			strBuilder.delete(0, strBuilder.length());
			try {
				buff.close();
				outSTr.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return 0;
	}
	
	
	public synchronized static int writePackageIntoFile(byte[] pkg,String node){
		String filename = UUID.randomUUID().toString();
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.bufferPath);
		strBuilder.append(node);
		strBuilder.append("/");
		//strBuilder.append(InitData.DR_BUFFER_DATA);
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		
		try {
			File f = new File(strBuilder.toString());
			f.setWritable(true);
			outSTr = new FileOutputStream(f);
			buff = new BufferedOutputStream(outSTr);
			buff.write(pkg);
			logger.info("保存文件" + strBuilder.toString() + "进buffer文件夹成功");
		} catch (FileNotFoundException e) {
			logger.error("保存文件" + strBuilder.toString() + "进buffer文件夹失败");
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error("保存文件" + strBuilder.toString() + "进buffer文件夹失败");
			logger.error(e.getMessage(), e);
		}
		finally{
			strBuilder.delete(0, strBuilder.length());
			try {
				buff.close();
				outSTr.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return 0;
	}
	
	public synchronized static int writePackageIntoFile(byte[] pkg){
		String filename = UUID.randomUUID().toString();
		String filenameSuffix = ".hex";
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(InitData.bufferPath);
		//strBuilder.append(InitData.DR_BUFFER_DATA);
		strBuilder.append(filename);
		strBuilder.append(filenameSuffix);
		BufferedOutputStream buff = null;
		FileOutputStream outSTr = null;
		
		try {
			File f = new File(strBuilder.toString());
			f.setWritable(true);
			outSTr = new FileOutputStream(f);
			buff = new BufferedOutputStream(outSTr);
			buff.write(pkg);
			logger.info("保存文件" + strBuilder.toString() + "进buffer文件夹成功");
		} catch (FileNotFoundException e) {
			logger.error("保存文件" + strBuilder.toString() + "进buffer文件夹失败");
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error("保存文件" + strBuilder.toString() + "进buffer文件夹失败");
			logger.error(e.getMessage(), e);
		}
		finally{
			strBuilder.delete(0, strBuilder.length());
			try {
				buff.close();
				outSTr.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return 0;
	}
}